﻿using BP.Plugin.Monitor.Application.Common.Interfaces;
using Core.Extensions;
using Core.Helpers;
using Core.Interfaces.Users;
using Core.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace BP.Plugin.Monitor.Application.Features.OnlineUsers.Commands.BatchDelete;

/// <summary>
/// 删除登录日志
/// </summary>
public class BatchDeleteOnlineLogCommand : IRequest<Result<bool>>
{
    /// <summary>
    /// 删除的ID集合
    /// </summary>
    public required List<long> Ids { get; set; }
}

public class BatchDeleteOnlineLogCommandHandler(IMonitorDbContext dbContext,ICurrentUserService currentUserService) : IRequestHandler<BatchDeleteOnlineLogCommand, Result<bool>>
{

    public async Task<Result<bool>> Handle(BatchDeleteOnlineLogCommand request, CancellationToken cancellationToken)
    {
        var logs = await dbContext.OnlineUsers
            .WhereIf(request.Ids.Count == 1 && request.Ids.Contains(0), x => currentUserService.Name == x.UserName) //清空当前用户日志
            .WhereIf(request.Ids.Count > 0 && !request.Ids.Contains(0), x => request.Ids.Contains(x.Id) && currentUserService.Name == x.UserName) //批量删除日志
            .ToListAsync(cancellationToken);
        ExceptionHelper.ThrowIfTrue(logs == null || !logs.Any(), "数据不存在");

        dbContext.OnlineUsers.RemoveRange(logs!);
        var result = await dbContext.SaveChangesAsync(cancellationToken) > 0;

        return await Result<bool>.SucceedAsync(result, result, ["删除失败"]);
    }
}
